iT邦幫忙

2022 iThome 鐵人賽

DAY 4
0
自我挑戰組

LeetCode Top 100 Liked系列 第 4

[Day 04] 3Sum (Medium)

  • 分享至 

  • xImage
  •  

15. 3Sum

Question

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0

  1. Notice that the solution set must not contain duplicate triplets

Example 1

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation: 
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.

Solution 1: Brute Force (TLE)

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)
        ans = []
        for i in range(n - 2):
            for j in range(i + 1, n - 1):
                for k in range(j + 1, n): 
                    if not (i != j and i != k and j != k):
                        continue
                    if nums[i] + nums[j] + nums[k] == 0:
                        tmpAns = [nums[i], nums[j], nums[k]]
                        # to remove duplicate ans
                        tmpAns.sort()
                        if tmpAns not in ans:
                            ans += [tmpAns]
        return ans

Time Complexity: O(N^3)
Space Complexity: O(N)

Solution 2: Hash

TODO

Time Complexity: O(N^2)
Space Complexity: O(N)

Solution 3: Two Pointer

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        n = len(nums)
        ans = []
        for i in range(n - 2):
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            
            l, r = i + 1, n - 1
            while l < r:
                threeSum = nums[i] + nums[l] + nums[r]
                if threeSum > 0:
                    r -= 1
                elif threeSum < 0:
                    l += 1
                else:
                    ans += [[nums[i], nums[l], nums[r]]]
                    l += 1
                    # to ignore duplicate ans
                    while l < r and nums[l] == nums[l - 1]:
                        l += 1
        return ans

Time Complexity: O(N^2)
Space Complexity: O(1)

Reference

https://leetcode.com/problems/3sum/discuss/2589188/100-Best-Solution-Explained

Follow-up: 16. 3Sum Closest

TODO

Time Complexity: O()
Space Complexity: O()

Follow-up: 18. 4Sum

TODO

Time Complexity: O()
Space Complexity: O()


上一篇
[Day 03] Longest Palindromic Substring (Medium)
下一篇
[Day 05] Maximum Subarray (Easy)、Reverse Integer (Easy)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言